<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');

$id = abs(intval($_GET['id']));
//pin
$act = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'dan';

$pin_id = isset($_REQUEST['pin_id']) ? intval($_REQUEST['pin_id']) : '0';
if($pin_id >0){
	$tmp_pin_order = Table::Fetch('pin_order', $pin_id);
	
	if($tmp_pin_order['state'] == 1)
	{
		
		$pin_id = 0;//重新开团
	}
	else if($tmp_pin_order['state'] == 2 || $tmp_pin_order['endtime'] <= time())
	{
		
		$pin_id = 0;//重新开团
	}
	
	
}else if($pin_id ==0 &&$act=='pin')//li shi order 
{
	$ex_con = array(
		'user_id' => $login_user_id,
		'team_id' => $id,
		'state' => 'unpay',
		'rstate' => 'normal',
		);
	$order = DB::LimitQuery('order', array(
		'condition' => $ex_con,
		'one' => true,
	));

	if($order){
		
		$pp_check = DB::LimitQuery('pin_order_list',array(
					'condition' => array('order_id'=>$order['id']),
					'one'=>true,
				));
		if($pp_check) {
			$pin_id = $pp_check['pin_id'];
			
			$tmp_pin_order = Table::Fetch('pin_order', $pin_id);
	
			if($tmp_pin_order['state'] == 1)
			{
				
				$pin_id = 0;//重新开团
			}
			else if($tmp_pin_order['state'] == 2 || $tmp_pin_order['endtime'] <= time())
			{
				
				$pin_id = 0;//重新开团
			}
		}
	}
}

$team = Table::Fetch('team', $id);
if ( !$team || $team['begin_time']>time() ) {
	Session::Set('error', '团购项目不存在');
	redirect( WEB_ROOT . '/index.php' );
}

/* 查询快递清单 */
if ($team['delivery'] == 'express') {
	$express_ralate = unserialize($team['express_relate']);
	foreach ($express_ralate as $k=>$v) {
		$express[$k] = Table::Fetch('category',$v['id']);
		$express[$k]['relate_data'] = $v['price'];
	}
}

/* 查询用户收货地址*/
	$c = array('user_id'=>$login_user_id);
	$address = DB::LimitQuery('address',array(
		'condition' => $c,
		'order' => 'ORDER BY id DESC',
	));
	$def = DB::LimitQuery('address',array(
		'condition' => array('user_id'=>$login_user_id,'default'=>'Y'),
		'one'=>true,
	));

	$default_addr = array();
	/* update area limit by fish 201508 begin*/
	//czone
	$is_js_arealimit = 0;
	$cityname = $city['name'];
	//var_dump($city);die();
	if(isset($INI['system']['areacondlimit']) && $INI['system']['areacondlimit']==1 && $cityname !='全国')
	{
		if(!empty($city['czone']))
		{
			//city
			$def = DB::LimitQuery('address',array(
				'condition' => array('user_id'=>$login_user_id,'province'=>$city['czone'],'city'=>$cityname),
				'one'=>true,
			));
		} else {
			$def = DB::LimitQuery('address',array(
				'condition' => array('user_id'=>$login_user_id,'province'=>$cityname),
				'one'=>true,
			));
		}
		
		$is_js_arealimit = 1;
	}
	/* update area limit by fish 201508 end*/
	if(!empty($def)) {
		$default_addr = $def;
	}

$ex_con = array(
		'user_id' => $login_user_id,
		'team_id' => $team['id'],
		'state' => 'unpay',
		'rstate' => 'normal',
		);
$order = DB::LimitQuery('order', array(
	'condition' => $ex_con,
	'one' => true,
));


//peruser buy count 删除数量限制
if ($team['per_number']>0 && false) {
	$now_count = Table::Count('order', array(
		'user_id' => $login_user_id,
		'team_id' => $id,
		'state' => 'pay',
	), 'quantity');
	$team['per_number'] -= $now_count;
	if ($team['per_number']<=0) {
		Session::Set('error', '您购买本单产品的数量已经达到上限，快去关注一下其他产品吧！');
		redirect( WEB_ROOT . "/team.php?id={$id}"); 
	}
}
else {
	if ($team['max_number']>0) $team['per_number'] = $team['max_number'] - $team['now_number'];
}

if ( $_POST  || !empty($default_addr)) {
	//var_dump($act);die();
	
	if(empty($default_addr)) {
	
		$addr_data = array();
		$addr_data['user_id'] = $login_user_id;
		$addr_data['province'] = $_POST['provinceId'];
		$addr_data['city'] = $_POST['cityId'];
		$addr_data['area'] = $_POST['areaId'];
		$addr_data['street'] = $_POST['adinfo'];
		$addr_data['name'] = $_POST['realname'];
		$addr_data['mobile'] = $_POST['mobile'];
		$addr_data['default'] = 'Y';
		$addr_data['zipcode'] = '';
		$addr_data['create_time'] = time();
		
		$addr_id  = DB::Insert('address', $addr_data);
		
		$address = DB::LimitQuery('address',array(
			'condition' => $c,
			'order' => 'ORDER BY id DESC',
		));
		$ck_def = DB::LimitQuery('address',array(
			'condition' => array('user_id'=>$login_user_id,'default'=>'Y'),
			'order' => 'ORDER BY id DESC',
			'one' => true
		));

		$default_addr = $addr_data;
		$default_addr['id'] = $ck_def['id'];
		
		//$express_id =$addr_id;
	} else {
		//$express_id =$default_addr['id'];
	}
	
	
	//array(1) { [0]=> array(2) { ["id"]=> string(2) "84" ["price"]=> string(4) "0.01" } }
	$express_node = array_pop($express);
	$express_id =  $express_node['id']; 

	
	$express_price = empty($express_node['relate_data']) ? 0 : $express_node['relate_data'];
	$condbuy = implode('@', $_POST['condbuy']);
	//var_dump( $_POST);die();
	isset($_POST['quantity']) ? '' : $_POST['quantity']=1;
	$table = new Table('order', $_POST);
	
	$table->quantity = abs(intval($table->quantity));

	if ($order && $order['state']=='unpay') {
		$table->SetPk('id', $order['id']);
	}

	$table->user_id = $login_user_id;
	$table->state = 'unpay';
	$table->allowrefund = $team['allowrefund'];
	$table->team_id = $team['id'];
	$table->partner_id = $team['partner_id'];
	
	$table->city_id = $team['city_id'];
	$table->express = ($team['delivery']=='express') ? 'Y' : 'N';
	$table->fare = $table->express=='Y' ? $express_price : 0;
	$table->express_id = $table->express=='Y' ? $express_id : 0;
	$table->price = $act == 'pin' ? $team['pin_price'] : $team['team_price'];
	$table->credit = 0;
	$table->condbuy = $condbuy;
	
	/*用户收货地址*/
	if ($team['delivery'] == 'express') {
		//if( $_POST['address-list'] && $_POST['address-list'] !='0' ){
		//	$address = Table::Fetch('address',$_POST['address-list']);
			$table->aid = $default_addr['id'];
			$table->realname = $default_addr['name'];
			$table->zipcode = $default_addr['zipcode'];
			$table->mobile = $default_addr['mobile'];
			$table->address = $default_addr['province']. $default_addr['city'] .$default_addr['area']. $default_addr['street'];
		//}
	}
	if ( $table->id ) {
		$eorder = Table::Fetch('order', $table->id);
		
		if ($eorder['state']=='unpay' 
				&& $eorder['team_id'] == $id
				&& $eorder['user_id'] == $login_user_id
		   ) {
			   
			 $is_pin =   ($act == 'pin') ? true : false;
			$table->origin = team_origin($team, $table->quantity,$express_price,$is_pin );
			//$table->origin -= $eorder['card'];
		} else {
			$eorder = null;
		}
	}
	if (!$eorder){
		$table->pk_value='';
		$table->create_time = time();
		 $is_pin =   $act == 'pin' ? true : false;
		$table->origin = team_origin($team, $table->quantity,$express_price,$is_pin );
		$table->is_pin =   $act == 'pin' ? 1 : 0;
	} else {
		$table->is_pin =   $act == 'pin' ? 1 : 0;
		if($act !='pin')
		{
			$sql = 'DELETE FROM `pin_order_list` where order_id='.$table->id;
			$rs =  DB::Query($sql);
		}
	}
	$table->commission_id = 0;
	$table->commission_money = 0;
	
	$table->commission_id = $login_user['shareid'];
	
	$table->commission_money = get_team_commission_money($team);
	$insert = array(
			'user_id','commission_id', 'commission_money','team_id','partner_id', 'city_id', 'state','is_pin','aid', 'express_id',
			'fare', 'express_xx','express', 'origin', 'price',
			'address', 'zipcode', 'realname', 'mobile', 
			'quantity', 'create_time', 'remark', 'condbuy',
		);
	if($team['allowrefund']=='Y') $insert[] = 'allowrefund' ;
	if ($flag = $table->update($insert)) {
		$order_id = abs(intval($table->id));
		
		if($act == 'pin')
		{
			//var_dump($eorder);die();
			//拼团开始
			if(!$eorder){
				//新订单，旧订单无需处理
				if($pin_id>0)
				{
					//邀请的拼团，无需插入pin_order表，只要新增该拼团记录
					//id,pin_id,order_id,createtime 
					$p_order_list = array();
					$p_order_list['pin_id'] = $pin_id;
					$p_order_list['order_id'] = $order_id;
					$p_order_list['createtime'] = time();
					DB::Insert('pin_order_list', $p_order_list);
				} else {
					/**
					pin_order 新开的 拼团，需要插入pin_order 表
					id,state,need_count,finish_time,createtime
					**/
					$pin_order = array();
					$pin_order['state'] = 0;
					$pin_order['need_count'] = $team['min_number'];
					$pin_order['finish_time'] = 0;
					$pin_order['createtime'] = time();
					$pin_order['endtime'] = time()+86400*$team['pin_day'];
					$pin_id = DB::Insert('pin_order', $pin_order);
					
					$p_order_list = array();
					$p_order_list['pin_id'] = $pin_id;
					$p_order_list['order_id'] = $order_id;
					$p_order_list['createtime'] = time();
					DB::Insert('pin_order_list', $p_order_list);
				}
				
			}  else {
				//检测是否存在这个pin_order_list记录
				$pp_check = DB::LimitQuery('pin_order_list',array(
					'condition' => array('order_id'=>$order_id),
					'one'=>true,
				));
				if($pp_check) {
					if($pin_id>0)
					{
						//createtime 可能引起的bug是 团长移位。
						$SQL = "UPDATE pin_order_list set pin_id='{$pin_id}',createtime=".time()." WHERE order_id = '{$order_id}' ;";
						$rs = DB::Query($SQL);
					}
				} else {
					$pin_order = array();
					$pin_order['state'] = 0;
					$pin_order['need_count'] = $team['min_number'];
					$pin_order['finish_time'] = 0;
					$pin_order['createtime'] = time();
					$pin_order['endtime'] = time()+86400*$team['pin_day'];
					
					$pin_id = DB::Insert('pin_order', $pin_order);
					
					$p_order_list = array();
					$p_order_list['pin_id'] = $pin_id;
					$p_order_list['order_id'] = $order_id;
					$p_order_list['createtime'] = time();
					DB::Insert('pin_order_list', $p_order_list);
					
				}
			}
		}
		
		
		/* 插入订单来源 */
		$data['order_id'] = $order_id;
		$data['user_id'] = $login_user_id;
		$data['referer'] = $_COOKIE['referer'];
		$data['create_time'] = time();
		DB::Insert('referer', $data);
		
		redirect(WEB_ROOT."/order/check.php?id={$order_id}");
	}
}


include template('team_buy');
